package kwic.architecture;

import java.io.*;
import java.util.*;

/**
 * 主程序-子程序体系结构实现KWIC。
 */
public class MainProgramSubroutine {
    private ArrayList<String> kwicList = new ArrayList<>();
    private ArrayList<String> lineTxt = new ArrayList<>();

    public static void main(String[] args) {
        MainProgramSubroutine kwic = new MainProgramSubroutine();
        kwic.input("src/main/resources/input.txt");
        kwic.shift();
        kwic.alphabetizer();
        kwic.output("src/main/resources/output2.txt");
    }

    /**
     * 读取输入文件内容。
     * @param fileName 输入文件名
     */
    public void input(String fileName) {
        try (BufferedReader inputFile = new BufferedReader(new FileReader(fileName))) {
            String line;
            while ((line = inputFile.readLine()) != null) {
                lineTxt.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入输出文件内容。
     * @param filename 输出文件名
     */
    public void output(String filename) {
        try (BufferedWriter outputFile = new BufferedWriter(new FileWriter(filename))) {
            for (String line : kwicList) {
                outputFile.write(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成所有可能的循环移位。
     */
    public void shift() {
        for (String line : lineTxt) {
            StringTokenizer token = new StringTokenizer(line);
            ArrayList<String> tokens = new ArrayList<>();
            while (token.hasMoreTokens()) {
                tokens.add(token.nextToken());
            }
            for (int i = 0; i < tokens.size(); i++) {
                String shiftedLine = String.join(" ", tokens);
                kwicList.add(shiftedLine);
                Collections.rotate(tokens, -1);
            }
        }
    }

    /**
     * 对移位后的结果进行字典序排序。
     */
    public void alphabetizer() {
        kwicList.sort(String::compareToIgnoreCase);
    }
}
